package com.yncmcc.Controller;

import com.mysql.cj.api.log.Log;
import com.sun.xml.internal.messaging.saaj.packaging.mime.internet.MimeUtility;
import com.yncmcc.Controller.Interface.FileDownController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * Created by CMCC-Sunmo on 2016/9/9.
 */
@Controller
@RequestMapping("/file")
public class FileDownControllerImpl implements FileDownController {

    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public String fileDownload(String fileName, HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName,"UTF-8"));
//        response.setHeader("Content-Disposition", "attachment;fileName=" + MimeUtility.encodeWord(fileName,"UTF-8","B"));

        if(fileName==null||fileName.equals("")){
            response.sendRedirect(request.getContextPath()+"/404.html");
            return null;
        }else {
            try {
                String path = Thread.currentThread().getContextClassLoader().getResource("").getPath() + "download";//这个download目录为啥建立在classes下的
                FileInputStream inputStream = new FileInputStream(new File(path + File.separator + fileName));
//                FileInputStream inputStream = new FileInputStream(new File("/home/lljy/server1/webapps/ContractMS/WEB-INF/classes/download" + File.separator + fileName));

                OutputStream os = response.getOutputStream();
                byte[] b = new byte[2048];
                int length;
                while ((length = inputStream.read(b)) > 0) {
                    os.write(b, 0, length);
                }

                // 这里主要关闭。
                os.close();

                inputStream.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            //  返回值要注意，要不然就出现下面这句错误！
            //java+getOutputStream() has already been called for this response
            return null;
        }
    }
}
